package com.eco.fanliapp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.*;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.*;
import com.eco.fanliapp.vo.AppUserFansTeamVo;
import com.eco.fanliapp.vo.ChannelUserAffiliationVo;
import com.eco.fanliapp.vo.WithdrawalInfo;
import com.eco.fanliapp.vo.respone.ResponeOrderResults.OrderDataBean;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * APP用户 服务层实现
 *
 * @author xiaoxx
 * @date 2019-04-24
 */
@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements IAppUserService {


    private static final Logger log = LoggerFactory.getLogger(AppUserServiceImpl.class);

    @Autowired
    private AppUserMapper appUserMapper;
    @Autowired
    private IAppWithdrawalService iAppWithdrawalService;
    @Autowired
    private AppWithdrawalMapper appWithdrawalMapper;
    @Autowired
    private IAppUserOrderService iAppUserOrderService;
    @Autowired
    private AppWithdrawalMapper withdrawalMapper;
    @Autowired
    private AppOrderDetailMapper orderDetailMapper;
    @Autowired
    private IAppOrderDetailService iAppOrderDetailService;
    @Autowired
    private ITaoBaoMethodService iTaoBaoMethodService;
    @Autowired
    private AppNewsLogMapper appNewsLogMapper;
    @Autowired
    private IAppCompanyService appCompanyService;
    @Autowired
    private IAppUserRedRewardService appUserRedRewardService;
    //    @Autowired
//    private Environment environment;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private UpdateUserCommon updateUserCommon;

    @Autowired
    private ISyBlacklistService iSyBlacklistService;

    @Autowired
    private RedisLockService redisLockService;

    @Autowired
    private ISyUserMoneyService syUserMoneyService;
    @Autowired
    private SyUserMoneyLogMapper syUserMoneyLogMapper;

    @Autowired
    private RedisTemplateService redisTemplateService;
    @Autowired
    private SyChannelUserMapper syChannelUserMapper;
    @Autowired
    private TaobaoSchemeMapper taobaoSchemeMapper;

    /**
     * 查询APP用户信息
     *
     * @param tableId APP用户ID
     * @return APP用户信息
     */
    @Override
    public AppUser selectAppUserById(Long tableId) {
        return appUserMapper.selectAppUserById(tableId);
    }

    /**
     * 查询APP用户列表
     *
     * @param appUser APP用户信息
     * @return APP用户集合
     */
    @Override
    public List<AppUser> selectAppUserList(AppUser appUser) {
        return appUserMapper.selectAppUserList(appUser);
    }

    /**
     * 新增APP用户
     *
     * @param appUser APP用户信息
     * @return 结果
     */
    @Override
    public int insertAppUser(AppUser appUser) {
        String userId = UUIDUtils.getByUserId();
        if (null != userId && !"".equals(userId)) {
            AppUser user = selectAppUserByUserId(Long.valueOf(userId));
            while (null != user && user.getUserId() != 0) {
                userId = UUIDUtils.getByUserId();
                user = selectAppUserByUserId(Long.valueOf(userId));
            }
            appUser.setUserId(Long.valueOf(userId));
            appUser.setUserCreateTime(System.currentTimeMillis());
            appUser.setUserUpdateTime(System.currentTimeMillis());
            appUser.setUserLoginTime(new Date());
            return appUserMapper.insertAppUser(appUser);
        } else {
            return 0;
        }
    }

    /**
     * 修改APP用户
     *
     * @param appUser APP用户信息
     * @return 结果
     */
    @Override
    public int updateAppUser(AppUser appUser) {
        appUser.setUserUpdateTime(System.currentTimeMillis());
        return appUserMapper.updateAppUser(appUser);
    }

    /**
     * 删除APP用户对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteAppUserByIds(String ids) {
        return appUserMapper.deleteAppUserByIds(Convert.toStrArray(ids));
    }

    @Override
    public AppUser selectAppUserByPhoneNumber(String phoneNumber) {
        // TODO Auto-generated method stub
        return appUserMapper.selectAppUserByPhoneNumber(phoneNumber);
    }

    @Override
    public AppUser selectAppUserByWechatUnionid(String wechatUnionid) {
        // TODO Auto-generated method stub
        return appUserMapper.selectAppUserByWechatUnionid(wechatUnionid);
    }

    @Override
    public ServerResponse<PageInfo> selectAppUserListByUserName(String userName, Integer currentPage, Integer pageSize, Integer companyId) {

        AppCompany appCompany = appCompanyService.selectAppCompanyById(companyId);
        if (appCompany.getType() == 1) {
            companyId = -1;
        }

        PageHelper.startPage(currentPage, pageSize);
        List<AppUser> appUsers = appUserMapper.selectAppUserListByUserName(userName, companyId);
        if (appUsers == null) {

            return ServerResponse.createByErrorMessage("查询失败");
        }
        return ServerResponse.createBySuccess("查询成功", new PageInfo(appUsers));
    }

    /**
     * 根据上级查询粉丝
     *
     * @return
     */
    @Override
    public List<AppUser> selectFansBySuperInviteCode(String meInviteCode) {

        return appUserMapper.selectFansBySuperInviteCode(meInviteCode);

    }


    /**
     * 根据微信ID下载用户
     *
     * @param wechatUnionid
     * @return
     */
    @Override
    public boolean downloadUserInformationByWechatUnionid(String wechatUnionid) {
        AppUser appUser = appUserMapper.downloadUserInformationByWechatUnionid(wechatUnionid);
        if (appUser == null) {
            return false;
        }
        String path = "E://user[" + System.currentTimeMillis() + "].xlsx";
        String name = "userInformation";
        List<String> titles = Lists.newArrayList();
        titles.add(PropertiesUtil.getProperty("userId"));
        titles.add(PropertiesUtil.getProperty("userName"));
        titles.add(PropertiesUtil.getProperty("userRealName"));
        titles.add(PropertiesUtil.getProperty("userWechatAuthorization"));
        titles.add(PropertiesUtil.getProperty("phoneNumber"));
        titles.add(PropertiesUtil.getProperty("alipayAccount"));
        titles.add(PropertiesUtil.getProperty("relationId"));
        titles.add(PropertiesUtil.getProperty("balance"));
        titles.add(PropertiesUtil.getProperty("totalWithdrawalAmount"));
        titles.add(PropertiesUtil.getProperty("promoteAmount"));
        titles.add(PropertiesUtil.getProperty("outstandingOrders"));
        titles.add(PropertiesUtil.getProperty("orderNumber"));
        titles.add(PropertiesUtil.getProperty("wechatUnionid"));
        titles.add(PropertiesUtil.getProperty("wechatNickname"));
        titles.add(PropertiesUtil.getProperty("userLastLoginTime"));
        titles.add(PropertiesUtil.getProperty("userStatus"));
        List<Map<String, Object>> values = Lists.newArrayList();
        Map<String, Object> map = Maps.newHashMap();
        map.put(PropertiesUtil.getProperty("userId"), appUser.getUserId());
        map.put(PropertiesUtil.getProperty("userName"), appUser.getUserName());
        map.put(PropertiesUtil.getProperty("userRealName"), appUser.getUserRealName());
        map.put(PropertiesUtil.getProperty("userWechatAuthorization"), "weixin");
        map.put(PropertiesUtil.getProperty("phoneNumber"), appUser.getPhoneNumber());
        map.put(PropertiesUtil.getProperty("alipayAccount"), appUser.getAlipayAccount());
        map.put(PropertiesUtil.getProperty("relationId"), appUser.getRelationId());
        map.put(PropertiesUtil.getProperty("balance"), appUser.getBalance());
        map.put(PropertiesUtil.getProperty("totalWithdrawalAmount"), appUser.getTotalWithdrawalAmount());
        map.put(PropertiesUtil.getProperty("promoteAmount"), appUser.getPromoteAmount());
        //未收货状态的订单数
        map.put(PropertiesUtil.getProperty("outstandingOrders"), 12);
        //全部订单数
        map.put(PropertiesUtil.getProperty("orderNumber"), 45);
        map.put(PropertiesUtil.getProperty("wechatUnionid"), appUser.getWechatUnionid());
        map.put(PropertiesUtil.getProperty("wechatNickname"), appUser.getWechatNickname());
        map.put(PropertiesUtil.getProperty("userLastLoginTime"), appUser.getUserLastLoginTime());
        map.put(PropertiesUtil.getProperty("userStatus"), appUser.getUserStatus());
        values.add(map);
        boolean flag = WriterExcelUtils.writerExcel(path, name, titles, values);
        return flag;
    }

    /**
     * 根据淘宝Id查询APP用户信息
     *
     * @param userId
     * @return APP用户信息
     */
    @Override
    public WithdrawalInfo selectAppUserByTaoBaoUserId(Long userId, Integer currentPage, Integer pageSize) {

        //根据用户id查询淘宝用户id
        AppUser user = appUserMapper.selectAppUserByUserId(userId);
        if (user == null) return null;
        AppUser appUser = appUserMapper.selectSuperUserInfoBySuperInviteCode(user.getSuperInviteCode());
        List<SyBlacklist> syBlacklists = iSyBlacklistService.selectAllSyBlacklist();
        for (SyBlacklist syBlacklist : syBlacklists) {
            if (user.getUserId().longValue() == syBlacklist.getUserId().longValue()) {
                user.setBlackScope(syBlacklist.getBlackScope());
                break;
            }
        }
        if (appUser != null) {
            user.setSuperAppUserName(appUser.getWechatNickname());
        }
        List<SyChannelUser> syChannelUsers = syChannelUserMapper.selectByUserId(user.getUserId());
        if (syChannelUsers != null && syChannelUsers.size() > 0) {
            user.setChannelInviteCode(syChannelUsers.get(0).getChannelInviteCode());
            user.setChannelInviteName(syChannelUsers.get(0).getChannelName());
        }
        BigDecimal bigDecimal = appWithdrawalMapper.userAmount(user.getUserId());
        if (bigDecimal != null) {
            user.setSumAmount(bigDecimal);
        }
        TaobaoScheme taobaoScheme = taobaoSchemeMapper.selectTaobaoSchemeById(user.getSchemeId());
        if(taobaoScheme != null ){
            user.setTaobaoName(taobaoScheme.getTaobaoName());
        }
        Long taobaoUserId = user.getTaobaoUserId();
        // 查看提现详情
        PageHelper.startPage(currentPage, pageSize);
        List<AppWithdrawal> withdrawalList = withdrawalMapper.selectAppWithdrawalByUserId(userId);
        if (withdrawalList == null) {
            return null;
        }
        PageInfo withdrawalListPageInfo = new PageInfo(withdrawalList);
        // 存放提现详情与订单详情
        HashMap<String, Object> map = new HashMap<>();
        WithdrawalInfo withdrawalInfo = new WithdrawalInfo();
        map.put("withdrawalListPageInfo", withdrawalListPageInfo);

        //提现总条数
        Integer withdrawalCount = withdrawalMapper.selectAppWithdrawalCountByUserId(userId);
        //提现总金额
        Double withdrawalAmount = withdrawalMapper.selectAppWithdrawalAmountByUserId(userId);
        withdrawalInfo.setTotalWithdrawalCount(withdrawalCount);
        withdrawalInfo.setTotalWithdrawalAmount(withdrawalAmount);


        // 查询根据淘宝用户id 查询商品订单详细信息
        PageHelper.startPage(currentPage, pageSize);
        List<AppOrderDetail> appOrderDetails = orderDetailMapper.findAppOrderDetailByTaobaoUserId(userId);
        PageInfo<AppOrderDetail> appOrderDetailPageInfo = new PageInfo<>(appOrderDetails);
        map.put("appOrderDetailPageInfo", appOrderDetailPageInfo);
        withdrawalInfo.setMap(map);
        //有效的订单条数
        Integer totalEffectiveItemCount = orderDetailMapper.selectTotalEffectiveItemCountByTaobaoUserId(userId);
        withdrawalInfo.setTotalEffectiveItemCount(totalEffectiveItemCount);
        // 退款总条数
        Integer totalRefundItemCount = orderDetailMapper.selectTotalRefundItemCountByTaobaoUserId(userId);
        withdrawalInfo.setTotalRefundItemCount(totalRefundItemCount);
        // 商品总佣金
        Double totalItemCommission = orderDetailMapper.selectTotalItemCommissionByTaobaoUserId(userId);
        withdrawalInfo.setTotalItemCommission(totalItemCommission);
        // 用户总佣金
        Double totalUserCommssion = appUserMapper.selectTotalUserCommssionByTaobaoUserId(userId);
        withdrawalInfo.setTotalUserCommssion(totalUserCommssion);
        int fensiSize = selectFansBySuperInviteCodeSum(user.getMeInviteCode());
        //用户微信余额
        SyUserMoney syUserMoney = syUserMoneyService.selectByUserId(userId);
        map.put("user", user);
        map.put("fensiSize", fensiSize);
        map.put("wxBalance", syUserMoney == null ? 0 : syUserMoney.getCashBalanceAmount());
        PageHelper.startPage(currentPage, pageSize);
        List<AppUser> onesFen = appUserMapper.findOnesFen(userId);
        PageInfo fen = new PageInfo(onesFen);
        //List<AppUser> twosFen = appUserMapper.findTwosFen(userId);
        map.put("onesFen", fen);
        //map.put("twosFen", twosFen);

        return withdrawalInfo;
    }

    //修改用户支付宝
    @Override
    public ServerResponse<JSONObject> updateAppUserAlipay(Long userId, String zname, String znumber, String phoneNumber) {
        // TODO Auto-generated method updateAppUserAlipay
        if (zname.length() >= 50) {
            return ServerResponse.createBySuccessMessage("姓名长度过长，请重新填写");
        }
        if (znumber.length() >= 50) {
            return ServerResponse.createBySuccessMessage("支付宝长度过长，请重新填写");
        }
        Integer type = 1;
        AppUser user = appUserMapper.selectAppUserByUserId(userId);
        if(user.getUserRealName() == null || user.getUserRealName().isEmpty()||user.getAlipayAccount() == null||user.getAlipayAccount().isEmpty()){
          type = 2;
        }
        int i = appUserMapper.updateAppUserAlipaytwo(userId, zname, znumber, phoneNumber);
        if (i > 0) {
          /*  QueryWrapper<SyUserTask> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.eq("task_type_id", 3);
            SyUserTask syUserTask = syUserTaskMapper.selectOne(queryWrapper);
            if (syUserTask == null) {
                updateUserCommon.UpdateUserMoney(new BigDecimal(0.2), userId, 3);
            }*/
            log.info("message修改用户支付宝成功{}", i);
            AppUser appUser = new AppUser();
            appUser.setUserId(userId);
            List<AppUser> appUsers = appUserMapper.selectAppUserList(appUser);
            if (appUsers.size() > 0) {
                for (AppUser appUser2 : appUsers) {
                    String[] str = {"taobaoUserId", "userRealName", "alipayAccount", "userId"};//需要返回的字段
                    if(type == 2){
                        return ServerResponse.createBySuccess("支付宝绑定成功", JsonUtils.objectToJsonIncludes(appUser2, str));
                    }
                    return ServerResponse.createBySuccess("支付宝修改成功", JsonUtils.objectToJsonIncludes(appUser2, str));
                }
            } else {
                return ServerResponse.createBySuccessMessage("用户不存在");
            }
            return ServerResponse.createBySuccessMessage("支付宝修改成功");
        } else {
            log.info("message修改用户支付宝失败{}", i);
            return ServerResponse.createByErrorMessage("支付宝修改失败");
        }
    }

    //新增用户支付宝信息
    @Override
    public ServerResponse<JSONObject> addAppUserAlipay(Long userId, String zname, String znumber, String phoneNumber) {
        // TODO Auto-generated method addAppUserAlipay
        int i = appUserMapper.updateAppUserAlipay(userId, zname, znumber, phoneNumber);
        if (i > 0) {
            log.info("message新增用户支付宝信息成功{}", i);
            AppUser appUser = new AppUser();
            appUser.setUserId(userId);
            List<AppUser> appUsers = appUserMapper.selectAppUserList(appUser);
            if (appUsers.size() > 0) {
                for (AppUser appUser2 : appUsers) {
                    String[] str = {"taobaoUserId", "userRealName", "alipayAccount", "userId"};//需要返回的字段
                    if (appUser2 != null) {
                        updateUserCommon.UpdateUserMoney(new BigDecimal(0.2), userId, 3);
//                    iSyUserMoneyService.usetTaskSuccessUpdateGold(3, userId);
                    }
                    return ServerResponse.createBySuccess("支付宝绑定成功", JsonUtils.objectToJsonIncludes(appUser2, str));
                }
            } else {
                return ServerResponse.createBySuccessMessage("用户不存在");
            }
            return ServerResponse.createBySuccessMessage("支付宝修改成功");
        } else {
            log.info("message新增用户支付宝信息失败{}", i);
            return ServerResponse.createByErrorMessage("支付宝修改失败");
        }
    }

    /*//绑定手机号
    @Override
    public ServerResponse<JSONObject> addAppUserAlipay(Long userId, String zname, String znumber,String phoneNumber) {
        // TODO Auto-generated method addAppUserAlipay
        int i = appUserMapper.updateAppUserAlipay(userId, zname, znumber,phoneNumber);
        if(i > 0) {
            log.info("message新增用户支付宝信息成功{}",i);
            AppUser appUser = new AppUser();
            appUser.setUserId(userId);
            List<AppUser> appUsers = appUserMapper.selectAppUserList(appUser);
            if(appUsers.size() > 0) {
                for (AppUser appUser2 : appUsers) {
                    String[] str = {"taobaoUserId","userRealName","alipayAccount","userId"};//需要返回的字段
                    return ServerResponse.createBySuccess("数据获取成功",JsonUtils.objectToJsonIncludes(appUser2, str));
                }
            }else {
                return ServerResponse.createBySuccessMessage("用户不存在");
            }
            return ServerResponse.createBySuccessMessage("支付宝修改成功");
        }else {
            log.info("message新增用户支付宝信息失败{}",i);
            return ServerResponse.createByErrorMessage("支付宝修改失败");
        }
    }
    */
    @Override
    @Transactional
    public int updateAppUserbalance(Long userId, BigDecimal money) {
        // TODO Auto-generated method updateAppUserbalance
        AppUser appUser = new AppUser();
        appUser.setUserUpdateTime(System.currentTimeMillis());
        appUser.setUserId(userId);
        updateAppUser(appUser);
        return appUserMapper.updateAppUserSubbalance(userId, money);
    }

    @Override
    public AppUser selectAppUserBybalance(Long userId) {
        // TODO Auto-generated method selectAppUserBybalance
        return appUserMapper.selectAppUserBybalance(userId);
    }

    /**
     * 下载全部用户信息
     *
     * @return
     */
    @Override
    public void downloadUserInformation(HttpServletResponse response, String username) {
        String fileName = "用户信息";
        List<AppUser> userList = appUserMapper.downloadUserInformation(username);
        String[] columnName = new String[]{"用户id", "用户名", "姓名", "推荐人",
                "手机号", "支付宝账号", "渠道ID", "可提现金额", "总提现金额", "推广金额",
                "订单数", "上级ID", "上级微信昵称", "最近登录时间", "注册时间"};
        List<Map<String, Object>> values = Lists.newArrayList();
        String[][] content = new String[userList.size()][columnName.length];
        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < userList.size(); i++) {
            content[i][0] = String.valueOf(userList.get(i).getUserId());
            content[i][1] = userList.get(i).getUserName();
            content[i][2] = userList.get(i).getUserRealName();
            content[i][3] = userList.get(i).getSuperWechatNickname();//推荐人

            content[i][4] = userList.get(i).getAlipayPhoneNumber();
            content[i][5] = userList.get(i).getAlipayAccount();
            content[i][6] = String.valueOf(userList.get(i).getRelationId());
            content[i][7] = String.valueOf(userList.get(i).getBalance());
            content[i][8] = String.valueOf(userList.get(i).getTotalWithdrawalAmount());
            content[i][9] = String.valueOf(userList.get(i).getPromoteAmount());

            content[i][10] = String.valueOf(userList.get(i).getOrderNumber());
            content[i][11] = userList.get(i).getSuperWechatUnionid();
            content[i][12] = userList.get(i).getSuperWechatNickname();
            if (userList.get(i).getUserLastLoginTime() != null && userList.get(i).getUserLastLoginTime() != 0) {
                content[i][13] = s.format(userList.get(i).getUserLastLoginTime().longValue());
            } else {
                content[i][13] = "";
            }
            if (userList.get(i).getUserCreateTime() != null && userList.get(i).getUserCreateTime() != 0) {
                content[i][14] = s.format(userList.get(i).getUserCreateTime().longValue());
            } else {
                content[i][14] = "";
            }
        }
        ExportExcelUtil.exportExcel(response, fileName, fileName, columnName, content, null);

    }

    /**
     * 分页查询用户信息
     * @param currentPage
     * @param pageSize
     * @return
     */
    /**
     * (non-Javadoc)
     *
     * @value: 在redis中 保存缓存在以user命名的集合中
     * @key :   user集合中的关键字，注意字符串要以单引号括住  '',变量前缀加#号，如#userId
     */
    @Override
    public ServerResponse selectAppUserListByPaging(Integer currentPage, Integer pageSize, Integer companyId, String userName) {

        int start = (currentPage - 1) * pageSize;
        HashMap<String, Object> map = new HashMap();
        map.put("companyId", companyId);
        map.put("userName", userName);
        map.put("currentPage", start);
        map.put("pageSize", pageSize);
        List<AppUser> appUsers = appUserMapper.selectAppUserListNew(map);
        Long total = appUserMapper.selectAppUserListNewCount(map);
        if (appUsers == null) {
            return ServerResponse.createByErrorMessage("查询失败");
        }
        List<SyBlacklist> syBlacklists = iSyBlacklistService.selectAllSyBlacklist();
        for (AppUser appUser : appUsers) {
            if (appUser.getCashBalanceAmount() == null) {
                appUser.setCashBalanceAmount(new BigDecimal(0));
            }
            for (SyBlacklist syBlacklist : syBlacklists) {
                if (appUser.getUserId().longValue() == syBlacklist.getUserId().longValue()) {
                    appUser.setBlackScope(syBlacklist.getBlackScope());
                    break;
                }
            }
        }

        IPage page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page();
        page.setRecords(appUsers);
        page.setCurrent(currentPage);
        page.setSize(pageSize);
        page.setTotal(total);

        return ServerResponse.createBySuccess("查询成功", page);
    }

    /**
     * 我的钱包的4个值（累计补贴，入账中，可提现，节省金额）
     *
     * @param userId
     * @return
     */
    @Override
    public ServerResponse<JSONObject> findAppUserBybalance(Long userId) {
        // TODO Auto-generated method selectAppUserBybalance
        JSONObject json = new JSONObject();
        //累计收益 = 可提现金额 + 已提现金额 + 提现中
        //团队收益 = 粉丝贡献

        //查询省了多少钱
        BigDecimal totalIncome = new BigDecimal(0);
        String redisKeyStr = "app_user_balance_spare_" + userId;

        if (redisTemplateService.hasKey(redisKeyStr)) {
            totalIncome = redisTemplateService.getTByKey(redisKeyStr, BigDecimal.class);
        }
        if (totalIncome == null || totalIncome.compareTo(new BigDecimal(0)) <= 0) {
            //查询已经结算的订单
            List<AppUserOrder> finshedOrders = iAppUserOrderService.selectUserOrder(userId);
            JdUserOrder finshedJdOrders = iAppUserOrderService.selectUserJdOrder(userId);
            PddUserOrder finshedPddOrders = iAppUserOrderService.selectUserPddOrder(userId);
            if(finshedJdOrders != null && finshedJdOrders.getCommission() != null){
                totalIncome = finshedJdOrders.getCommission();
            }
            if(finshedPddOrders != null && finshedPddOrders.getSpareMoney() != null){
                BigDecimal pddSpareMoney = new BigDecimal(finshedPddOrders.getSpareMoney()).divide(new BigDecimal("100"));
                totalIncome = totalIncome.add(pddSpareMoney);
            }
            //计算节省金额
            if (finshedOrders == null || finshedOrders.size() <= 0) {
                json.put("totalIncome", totalIncome);
            } else {
                for (AppUserOrder appUserOrder : finshedOrders) {
                    totalIncome = totalIncome.add((appUserOrder == null || appUserOrder.getSpareMoney() == null) ? new BigDecimal(0) : appUserOrder.getSpareMoney());
                }
                json.put("totalIncome", totalIncome);
            }
            if (totalIncome != null) {
                redisTemplateService.set(redisKeyStr, totalIncome, 60 * 5);
            }
        } else {
            json.put("totalIncome", totalIncome);
        }

        //查询入账中
        BigDecimal rzz = new BigDecimal("0");
        AppUserOrder tbrz = iAppUserOrderService.selectAppUserOrderBybalanceCount(userId);
        JdUserOrder jdrz = iAppUserOrderService.selectJdOrderBybalanceCount(userId);
        PddUserOrder pddrz = iAppUserOrderService.selectPddOrderBybalanceCount(userId);
        if(tbrz != null && tbrz.getCommission() != null){
            rzz = tbrz.getCommission();
        }
        if(jdrz != null && jdrz.getCommission() != null){
            rzz = rzz.add(jdrz.getCommission());
        }
        if(pddrz != null && pddrz.getCommission() != null){
            rzz = rzz.add(new BigDecimal(pddrz.getCommission()).divide(new BigDecimal("100")));
        }
        json.put("withdrawable2", rzz);
        //可提现余额
        AppUser ktx = selectAppUserBybalance(userId);
        if (ktx == null) {
            return ServerResponse.createByErrorCodeMessage(505, "用户数据获取失败！！");
        }

        //构建返回json
        json.put("withdrawable3", BigDecimalUtils.Format(ktx.getBalance()));

        //提现中
        HashMap<String, Object> hashMap3 = iAppWithdrawalService.selectAppWithdrawalBybalanceCount(userId, 1);
        MapValueHelper helper3 = new MapValueHelper(hashMap3);
        helper3.getBigDecimal("amount");
        //已提现金额
        HashMap<String, Object> hashMap4 = iAppWithdrawalService.selectAppWithdrawalBybalanceCount(userId, 2);
        MapValueHelper helper4 = new MapValueHelper(hashMap4);
        helper4.getBigDecimal("amount");

        //构建返回json
        json.put("withdrawable1", BigDecimalUtils.Format(ktx.getBalance()).add(helper4.getBigDecimal("amount")).add(helper3.getBigDecimal("amount")));

        log.info("我的钱包的4个值（累计补贴，入账中，可提现，节省金额）message{}", json.toJSONString());
        return ServerResponse.createBySuccess("数据获取成功", json);
    }

    //我的团队下面的粉丝贡献
    @Override
    public ServerResponse<List<Map<String, Object>>> teamOrderDetail(
            Long userId, String name, Integer pageNum, Integer pageSize) {
        // TODO Auto-generated method teamOrderDetail
        pageNum = pageNum == null ? 0 : pageNum;
        pageSize = pageSize == null ? 20 : pageSize;
        List<Map<String, Object>> objects = new ArrayList<Map<String, Object>>();

        List<AppUser> users = appUserMapper.teamInviteUserList(userId, name, pageNum, pageSize);
        if (users.size() > 0) {
            for (AppUser appUser : users) {
                Double gxsr = iAppUserOrderService.findBalanceListByUserId(appUser.getUserId(), 2);
                Map<String, Object> object = new LinkedHashMap<>();
                object.put("name", appUser.getUserName());
                object.put("type", "直属粉丝");
                object.put("gxsr", gxsr == null ? 0 : gxsr);
                objects.add(object);
            }

            //排序
            Collections.sort(objects, new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    return (Double) o1.get("gxsr") < (Double) o2.get("gxsr") ? 1 : (o1.get("gxsr") == o2.get("gxsr") ? 0 : -1);//从大到小
                }
            });

        }

		/*//用我的邀请吗查询我的下级
		List<AppUser> userList = selectFansBySuperInviteCode(user.getMeInviteCode());
		for (AppUser appUser : userList) {
			Double gxsr = iAppUserOrderService.findBalanceListByUserId(appUser.getUserId(),2);

				Map<String, Object> object = new LinkedHashMap<>();
				object.put("name", appUser.getUserName());
				object.put("type", "直属粉丝");
				object.put("gxsr", gxsr);
				objects.add(object);
		}*/

        //间接粉丝，暂定关闭
		/*HashMap<String, Object> hashMap2 = iAppUserOrderService.findBalanceByUserIdSum(userId,3);
		MapValueHelper helper2 = new MapValueHelper(hashMap2);
		AppUser user2 = appUserMapper.selectAppUserListByTaoBaoUserId(helper2.getLong("taobaoUserId"));
		object1.put("name", user2.getUserName());
		object1.put("type", "间接粉丝");
		object1.put("gxsr", BigDecimalUtils.Format(helper2.getBigDecimal("commission")));
		if(helper2.getBigDecimal("commission").compareTo(BigDecimal.valueOf(0)) > 0) {
			objects.add(object1);
		}*/
        return ServerResponse.createBySuccess("数据获取成功", objects);
    }


    // 我的团队
    @Override
    public ServerResponse<Map<String, Object>> teamAll(Long userId) {
        // TODO Auto-generated method teamAll
        AppUser user = appUserMapper.selectAppUserByUserId(userId);
        if (user != null) {
            Map<String, Object> json = new LinkedHashMap<>();//用于构建返回
            //直属
            Integer zsfs = selectFansBySuperInviteCodeSum(user.getMeInviteCode());
            zsfs = zsfs == null ? 0 : zsfs;
            //直属粉丝邀请
			/*Integer zsfsyq = selectFansBySuperInviteMeInviteCodeSum(user.getMeInviteCode());
			zsfsyq = zsfsyq == null?0:zsfsyq;*/
            //构建返回数据
            json.put("zsfs", zsfs);
            //间接粉丝，暂定关闭
			/*		json.put("zsfsyq", zsfsyq);
			json.put("zsfszrs", (zsfs+zsfsyq));*/
            json.put("zsfszrs", (zsfs));

            //总贡献钱数
            double zgx = iAppUserOrderService.findBalanceListByUserId(userId, 0);
            json.put("zgx", zgx);
            //今日人数
            List<AppUser> users = selectFansBySuperInviteCode(user.getMeInviteCode());
            if (users.size() > 0) {
                Integer jrzsfs = 0;
                Integer jrzsfsyq = 0;
                Integer zrzsfs = 0;
                Integer zrzsfsyq = 0;
                for (AppUser appUser : users) {
                    //今天时间
                    Long l = Long.valueOf(DateFormatUtils.stampToDate(System.currentTimeMillis())) - 1;
                    l = Long.valueOf(DateFormatUtils.stampToDate2(DateFormatUtils.getYesterdayEndTime(), DateFormatUtils.STANDARD_FORMAT2));

                    if (appUser.getSuperInviteCode().equalsIgnoreCase(user.getMeInviteCode())) {
                        if (DateFormatUtils.stampToDate2(System.currentTimeMillis(), DateFormatUtils.STANDARD_FORMAT2).equals(
                                DateFormatUtils.stampToDate2(appUser.getUserCreateTime(), DateFormatUtils.STANDARD_FORMAT2))) {
                            jrzsfs++;
                        } else if ((long) l == (long) Long.valueOf(DateFormatUtils.stampToDate2(appUser.getUserCreateTime(), DateFormatUtils.STANDARD_FORMAT2))) {//昨天时间
                            zrzsfs++;
                        }
                    } else {
                        if (DateFormatUtils.stampToDate2(System.currentTimeMillis(), DateFormatUtils.STANDARD_FORMAT2).equals(DateFormatUtils.stampToDate2(appUser.getUserCreateTime(), DateFormatUtils.STANDARD_FORMAT2))) {
                            jrzsfsyq++;
                        } else if ((long) l == (long) Long.valueOf(DateFormatUtils.stampToDate2(appUser.getUserCreateTime(), DateFormatUtils.STANDARD_FORMAT2))) {//昨天时间
                            zrzsfsyq++;
                        }
                    }
                }
                json.put("jrzsfs", jrzsfs == null ? 0 : jrzsfs);
                //间接粉丝，暂定关闭
				/*	json.put("jrzsfsyq", jrzsfsyq== null?0:jrzsfsyq);
				json.put("jrzsfszrs", (jrzsfs+jrzsfsyq));*/
                json.put("jrzsfszrs", (jrzsfs));
                json.put("zrzsfs", zrzsfs == null ? 0 : zrzsfs);
                //间接粉丝，暂定关闭
				/*	json.put("zrzsfsyq", zrzsfsyq== null?0:zrzsfsyq);
				json.put("zrzsfszrs", (zrzsfs+zrzsfsyq));*/
                json.put("zrzsfszrs", (zrzsfs));

            } else {
                json.put("jrzsfs", 0);
                //间接粉丝，暂定关闭
                //	json.put("jrzsfsyq", 0);
                json.put("jrzsfszrs", 0);
                json.put("zrzsfs", 0);
                //间接粉丝，暂定关闭
                //	json.put("zrzsfsyq", 0);
                json.put("zrzsfszrs", 0);
            }
            return ServerResponse.createBySuccess("数据获取成功", json);
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "没有更多数据了");
        }
    }


    /**
     * 我的粉丝--粉丝人数 粉丝贡献
     *
     * @param userId
     * @return
     */
    @Override
    public ServerResponse<Map<String, Object>> teamFans(Long userId) {
        // TODO Auto-generated method teamAll
        AppUser user = appUserMapper.selectAppUserByUserId(userId);
        if (user != null) {
            //用于构建返回
            Map<String, Object> json = new LinkedHashMap<>();

            //粉丝人数
            Integer yqhy = selectFansBySuperInviteCodeSum(user.getMeInviteCode());
            yqhy = yqhy == null ? 0 : yqhy;
            json.put("yqhy", yqhy);

            //直属粉丝贡献钱数
            double ljtz = iAppUserOrderService.findBalanceListByUserId(userId, 2);
            json.put("ljtz", ljtz);

            return ServerResponse.createBySuccess("数据获取成功", json);
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "没有更多数据了");
        }
    }

    //用上级的邀请码查询自己的上级
    @Override
    public AppUser selectSuperUserInfoBySuperInviteCode(String superInviteCode) {
        // TODO Auto-generated method selectSuperUserInfoBySuperInviteCode
        return appUserMapper.selectSuperUserInfoBySuperInviteCode(superInviteCode);
    }

    //渠道ID查询
    @Override
    public AppUser selectUserInfoByRelationId(Long relationId) {
        // TODO Auto-generated method stub
        return appUserMapper.findUserInfoByRelationId(relationId);
    }

    //会员ID查询
    @Override
    public AppUser selectUserInfoBySpecialId(Long specialId) {
        // TODO Auto-generated method stub
        return appUserMapper.findUserInfoBySpecialId(specialId);
    }

    // 增加可提现金额
    @Override
    public int updateAppUseraddbalance(Long userId, BigDecimal commission) {
        // TODO Auto-generated method stub
        return appUserMapper.updateAppUseraddbalance(userId, commission);
    }

    //我的团队订单
    @Override
    public ServerResponse<List<OrderDataBean>> TeamOrder(
            Long appUserId, Integer tkStatus, Integer pageNum, Integer pageSize) {
        // TODO Auto-generated method TeamOrder
        pageNum = pageNum == null ? 0 : pageNum;
        pageSize = pageSize == null ? 20 : pageSize;
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        //查出我的渠道ID和我的邀请码
        AppUser user = appUserMapper.findRelationIdANDMeInviteCode(appUserId);
        //根据我的邀请吗查出我下级的渠道ID和邀请码
        List<AppUser> users = appUserMapper.findLevalRelationIdANDMeInviteCode(user.getMeInviteCode());
        List<OrderDataBean> results = new ArrayList<>();
        List<OrderDataBean> results2 = null;
        if (users.size() > 0) {
            for (AppUser appUser : users) {
                //根据我下级的渠道ID查询下级订单
                List<AppOrderDetail> details2 = iAppOrderDetailService.findTeamLevalOrderList(appUser.getRelationId(), appUser.getSpecialId(), tkStatus, pageNum, pageSize);
                if (details2.size() > 0) {
                    results = iTaoBaoMethodService.getTeamOrderDetail(appUserId, appUser.getUserId(), details2, 1);
                }
                //间接粉丝，暂定关闭
			/*	//查出我下级的下级的渠道ID
				List<AppUser> users2 = appUserMapper.findLeval2RelationIdANDMeInviteCode(appUser.getMeInviteCode());
				if(users2.size() > 0) {
					for (AppUser appUser2 : users2) {
						//根据我下级的下级的渠道ID查询订单
						List<AppOrderDetail> details3 = iAppOrderDetailService.findTeamLeval2OrderList(appUser2.getRelationId(),appUser.getSpecialId(),tkStatus,pageNum,pageSize);
						if(details3.size() > 0) {
							//map.put("jjfs", details3);
							results2 = iTaoBaoMethodService.getTeamOrderDetail(appUserId,appUser2.getUserId(),details3,2);
							results.addAll(results2);
						}
					}//for结束
				}*/
            }//for结束
            if (results != null && results.size() > 0) {
                map.put("list", results);
                return ServerResponse.createBySuccess("数据获取成功", results);
            } else {
                return ServerResponse.createBySuccessCodeMessage(201, "没有更多订单");
            }
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "没有更多订单");
        }
    }

    //累计收益查询
    @Override
    public ServerResponse<Map<String, Object>> findbalanceIncome(Long userId) {
        // TODO Auto-generated method findbalanceIncome
        Map<String, Object> json = new LinkedHashMap<>();//用于构建返回
        AppUser user = appUserMapper.selectAppUserByUserId(userId);
        //查询累计收益 = 我的收益 + 团队收益
        //我的收益 = 可提现金额 + 已提现金额 + 提现中
        //团队收益 = 粉丝贡献

        //查询入账中
        AppUserOrder rz = iAppUserOrderService.selectAppUserOrderBybalanceCount(userId);
        if (rz != null && rz.getCommission() != null) {
            log.info("message入账中金额{}", BigDecimalUtils.Format(rz.getCommission()));
            //构建返回json
            json.put("rzz", BigDecimalUtils.Format(rz.getCommission()));
        } else {
            json.put("rzz", 0);
        }

        //可提现余额
        AppUser ktx = selectAppUserBybalance(userId);
        if (null == ktx) {
            ktx.setBalance(BigDecimal.valueOf(0));
        }
        log.info("message可提现余额{}", BigDecimalUtils.Format(ktx.getBalance()));
        json.put("ktxje", BigDecimalUtils.Format(ktx.getBalance()));//构建返回json

        //提现中
        HashMap<String, Object> hashMap3 = iAppWithdrawalService.selectAppWithdrawalBybalanceCount(userId, 1);
        MapValueHelper helper3 = new MapValueHelper(hashMap3);
        BigDecimal txz = helper3.getBigDecimal("amount");

        //已提现金额
        HashMap<String, Object> hashMap4 = iAppWithdrawalService.selectAppWithdrawalBybalanceCount(userId, 2);
        MapValueHelper helper4 = new MapValueHelper(hashMap4);

        BigDecimal ytx = helper4.getBigDecimal("amount");

        //粉丝贡献
        //一级粉丝贡献
        HashMap<String, Object> hashMap = iAppUserOrderService.findBalanceByUserIdSum(userId, 2);
        MapValueHelper helper = new MapValueHelper(hashMap);
/*		//二级粉丝贡献
		HashMap<String, Object> hashMap2 = iAppUserOrderService.findBalanceByUserIdSum(userId,3);
		MapValueHelper helper2 = new MapValueHelper(hashMap2);
		BigDecimal fsgx = helper.getBigDecimal("commission").add(helper2.getBigDecimal("commission"));*/
        BigDecimal fsgx = helper.getBigDecimal("commission");

		
		/*//我的收益 ---个人收益
		json.put("wdsy", BigDecimalUtils.Format(ktx.getBalance()).add(ytx).subtract(fsgx));*/
        //粉丝贡献
        json.put("fsgx", fsgx);

        //累计收益---实际为个人收益
        json.put("ljsy", BigDecimalUtils.Format(ktx.getBalance()).add(ytx).add(txz).subtract(fsgx));

        return ServerResponse.createBySuccess("数据获取成功", json);
    }

    /**
     * 累计补贴-查询 订单补贴 粉丝贡献 订单数量，总收益
     *
     * @param userId
     * @return
     */
    @Override
    public ServerResponse<Map<String, Object>> findBalanceIncome(Long userId) {
        // TODO Auto-generated method findbalanceIncome
        Map<String, Object> json = new LinkedHashMap<>();//用于构建返回
        Integer orderCount = 0;
        Integer fansOrderCount = 0;

        //补贴收益
        double btdd = iAppUserOrderService.findBalanceListByUserId(userId, 1);
        json.put("btdd", btdd);

        QueryWrapper<AppUserOrder> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("order_grade", 1);
        orderCount = iAppUserOrderService.count(queryWrapper);

        json.put("orderCount", orderCount);

        //直属粉丝贡献钱数
        double fsgx = iAppUserOrderService.findBalanceListByUserId(userId, 2);
        //粉丝贡献
        json.put("fsgx", fsgx);

        //查询粉丝订单数量
        QueryWrapper<AppUserOrder> queryWrapper_fans = new QueryWrapper();
        queryWrapper_fans.eq("user_id", userId);
        queryWrapper_fans.eq("order_grade", 2);
        fansOrderCount = iAppUserOrderService.count(queryWrapper_fans);

        //粉丝订单数量
        json.put("fansOrderCount", fansOrderCount);
        //总收益
        json.put("sumIncome", btdd + fsgx);
        return ServerResponse.createBySuccess("数据获取成功", json);
    }

    //我的订单补贴
    @Override
    public ServerResponse findAllowance(Long appUserId) {
        // TODO Auto-generated method findAllowance 查询我的的补贴
        BigDecimal sumA = appNewsLogMapper.findAllowance(appUserId);
        sumA = sumA == null ? BigDecimal.valueOf(0) : sumA;
        return ServerResponse.createBySuccess("数据获取成功", sumA);
    }

    @Override
    public ServerResponse findInvitationFenSiCount(Long appUserId) {
        // TODO Auto-generated method findInvitationFenSiCount 查询我的助力红包邀请
        Map<String, Object> json = new HashMap<String, Object>();
        Integer hbcs = isCount(appUserId);
        if (hbcs != null && hbcs != 0) {
            json.put("surplus", hbcs);//剩余次数
        } else {
            json.put("surplus", 0);//为空代表次数已经用完了
        }
        json.put("total", ApiEnum.FENS_COUNT);//红包总次数
        json.put("money", ApiEnum.FENS_MONEY);//红包的钱数
        AppUser user = appUserMapper.selectAppUserByUserId(appUserId);
        Boolean boolean1 = is30Time(user.getUserCreateTime());
        if (boolean1) {
            json.put("isexpire", 2);//2是没有过期
        } else {
            json.put("isexpire", 1);//1是已过期
        }
        return ServerResponse.createBySuccess("数据获取成功", json);
    }

    //查询用户邀请次数
    private Integer isCount(Long userId) {
        Integer count = appNewsLogMapper.findFenSiCount(userId);
        count = count == null ? 0 : count;
        if (count <= ApiEnum.FENS_COUNT) {
            return ApiEnum.FENS_COUNT - count;
        } else {
            return 0;
        }
    }

    /**
     * 根据用户id，微信openid,淘宝id，查询APP用户列表
     *
     * @param appUser
     * @return
     */
    @Override
    public List<AppUser> selectAppUserListByUnionId(AppUser appUser) {
        return appUserMapper.selectAppUserListByUnionId(appUser);
    }

    /**
     * 修改APP用户授权首次登录
     *
     * @param appUser 修改APP用户授权首次登录
     * @return 结果
     */
    @Override
    public int updateAppLogin(AppUser appUser) {
        return appUserMapper.updateAppLogin(appUser);
    }

    //邀请赚钱，邀请人数，入账中，躺赚
   /* @Override
    public ServerResponse invitationMakeMoney(Long userId) {
        JSONObject json = new JSONObject();
        json.put("makeProfits", environment.getProperty("REDMONEY"));
        //已邀请人数
        int fsCount = appUserMapper.selectCountFS(userId);
        json.put("fsCount", fsCount);
        //查询入账中
		*//*AppUserOrder rz = iAppUserOrderService.selectAppUserOrderBybalanceCount(userId);
		if (rz != null && rz.getCommission() != null) {
			log.info("message入账中金额{}", BigDecimalUtils.Format(rz.getCommission()));
			json.put("withdrawable2", BigDecimalUtils.Format(rz.getCommission()));
		} else {
			json.put("withdrawable2", 0);
		}*//*
        int moneyCount = appUserRedRewardService.selectCountByStatusType("(2)", "(2)");
        json.put("withdrawable2", moneyCount);
        //可提现余额
        AppUser ktx = selectAppUserBybalance(userId);
        if (null == ktx) {
            ktx.setBalance(BigDecimal.valueOf(0));
        }
        log.info("message可提现余额{}", BigDecimalUtils.Format(ktx.getMakeRedMoney()));
        json.put("withdrawable3", ktx.getMakeRedMoney());//构建返回json
        log.info("message{}", json.toJSONString());
        return ServerResponse.createBySuccess("数据获取成功", json);
    }*/


    @Override
    public ServerResponse<JSONObject> addAlipayPhoneNumber(Long userId, String phoneNumber, String code) {

        String verifyCode = (String) redisTemplate.opsForValue().get(phoneNumber);
        verifyCode = verifyCode == null ? "" : verifyCode;
        if (!verifyCode.equals(code)) {
            return ServerResponse.createByErrorMessage("验证码错误");
        } else {
            int i = appUserMapper.updateAlipayPhoneNumber(phoneNumber, userId);

            if (i > 0) {
                AppUser appUser = appUserMapper.selectAppUserByUserId(userId);
                if (appUser != null) {
                    updateUserCommon.UpdateUserMoney(new BigDecimal(0.2), userId, 3);
//                    iSyUserMoneyService.usetTaskSuccessUpdateGold(3, userId);
                }
                return ServerResponse.createBySuccessMessage("手机号绑定成功");
            } else {
                return ServerResponse.createByErrorMessage("手机号绑定失败");
            }
        }
    }

    @Override
    public int updateBalance(BigDecimal hbMoney, Long userId) {
        return appUserMapper.updateBalance(hbMoney, userId);
    }

    /**
     * 我的团队-->>我的下级
     *
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ServerResponse<List<AppUserFansTeamVo>> findFansTeamList(Long userId, Integer pageNum, Integer pageSize) {
        pageNum = pageNum == null ? 0 : pageNum;
        pageSize = pageSize == null ? 20 : pageSize;
        List<AppUserFansTeamVo> list = iAppUserOrderService.findFansTeamList(userId, pageNum, pageSize);

        return ServerResponse.createBySuccess("粉丝列表获取成功", list);
    }

    @Override
    public AppUser selectAppUserByAlipayPhoneNumber(String phoneNumber) {
        return appUserMapper.selectAppUserByAlipayPhoneNumber(phoneNumber);
    }

    //邀请赚钱，邀请人数，入账中，躺赚
    @Override
    public ServerResponse invitationMakeMoney(Long userId) {
        Map redMap = appUserRedRewardService.invitationMakeMoneyCash(userId);
        JSONObject json = new JSONObject();
        json.put("makeProfits", 5);
        //已邀请人数
        int fsCount = appUserMapper.selectCountFS(userId);
        json.put("fsCount", fsCount);
        json.put("withdrawable2", redMap.get("notReceived"));
        json.put("withdrawable3", redMap.get("waitreceived"));//构建返回json
        return ServerResponse.createBySuccess("数据获取成功", json);
    }


    @Override
    public ServerResponse invitationMakeMoneyCash(Long userId) {
        //查询红包类型为2的已领取和未领取的总数
        Map redMap = appUserRedRewardService.invitationMakeMoneyCash(userId);
        JSONObject json = new JSONObject();
        int fsCount = appUserMapper.selectCountFS(userId);
        json.put("fsCount", fsCount);
        json.put("notReceived", redMap.get("notReceived"));
        json.put("received", redMap.get("received"));//构建返回json
        return ServerResponse.createBySuccess("邀请明细数据获取成功", json);
    }

    @Override
    public List<AppUser> selectUserByUserNameAndAlipayAccount(String userRealName, String alipayAccount) {
        return appUserMapper.selectUserByUserNameAndAlipayAccount(userRealName, alipayAccount);
    }

    @Override
    public ServerResponse insertAlipayPhoneNumber(Long userId, String zname, String znumber, String phoneNumber) {
        //redis锁-时间
        long startTimes = System.currentTimeMillis() + 1000 * 3;

        //获取锁
        if (!redisLockService.lock(userId + "insertAlipayPhoneNumber" + phoneNumber, startTimes + "")) {
            log.info("操作频繁，用户Id={}，手机号={}，记录时间={}", userId, phoneNumber, new Date());
            return ServerResponse.createByErrorMessage("您操作太频繁了，3秒后再试吧");
        }
        HashMap map = new HashMap();
        AppUser appUser2 = appUserMapper.selectAppUserByUserId(userId);
        if (appUser2 != null) {
            //修改用户信息，绑定支付宝
            int i = appUserMapper.updateAppUserAlipay(userId, zname, znumber, phoneNumber);
            if (i > 0) {
                log.info("message用户支付宝信息绑定成功{}", i);
                int ii = updateUserCommon.UpdateUserMoney(new BigDecimal(0.2), userId, 3);
                if (ii > 0) {
                    map.put("title", "完善手机号奖励");
                    map.put("moneyNum", 0.2);
                    map.put("displayTime", ApiEnum.DIS_TIME);//弹窗显示时间2秒
                    map.put("popup", true);//true 弹窗
                    return ServerResponse.createBySuccess("绑定成功", map);
                } else {
                    return ServerResponse.createByErrorMessage("奖励领取失败");
                }
            } else {
                log.info("message新增用户支付宝信息失败{}", i);
                return ServerResponse.createByErrorMessage("用户信息错误");
            }
        } else {
            return ServerResponse.createByErrorMessage("用户信息错误");
        }
    }

    @Override
    public int updateBatchByCompanyId(String inviteCode, String minviteCode, Integer companyId) {
        //批量更新根据公司id
        int i = appUserMapper.updateBatchByCompanyId(inviteCode, minviteCode, companyId);
        return i;
    }

    @Override
    public Double totalInvitationCost(Integer companyId, Integer flag) {
        return appUserMapper.totalInvitationCost(companyId, flag);
    }

    @Override
    public int invitationExpenseYesterday() {
        return appUserMapper.invitationExpenseYesterday();
    }

    @Override
    public int totalNumberYesterday(Integer companyId, Integer flag) {
        return appUserMapper.totalNumberYesterday(companyId, flag);
    }

    @Override
    public int numberOfInvitations(Integer flag, Integer companyId) {
        return appUserMapper.numberOfInvitations(flag, companyId);
    }

    @Override
    public List<AppUser> queryAppUserSm(Integer logType) {

        return appUserMapper.queryAppUserSm(logType);
    }

    @Override
    public List<AppUser> sendCopyLinkMessage() {
        return appUserMapper.sendCopyLinkMessage();
    }

    /**
     * 签到30天没有签到加入黑名单用户
     *
     * @return
     */
    @Override
    public List<AppUser> selectUserNotOrder() {
        return appUserMapper.selectUserNotOrder();
    }

    @Override
    public List<Long> updateUserNotOrderBlack() {
        return appUserMapper.updateUserNotOrderBlack();
    }

    @Override
    public ServerResponse<PageInfo> findUserOnesFen(Long userId, int currentPage, int pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        List<AppUser> onesFen = appUserMapper.findOnesFen(userId);
        return ServerResponse.createBySuccess("查找成功", new PageInfo(onesFen));
    }


    private List<AppUser> selectFansByLevelInviteCode(String meInviteCode) {
        // TODO Auto-generated method stub
        return appUserMapper.selectFansByLevelInviteCode(meInviteCode);
    }

    private int selectFansDaySuperInviteCodeSum(String meInviteCode, Long sj) {
        // TODO Auto-generated method selectFansYesterdaySum
        return appUserMapper.selectFansDaySuperInviteCodeSum(meInviteCode, sj);
    }

    private int selectFansDaySuperInviteMeInviteCodeSum(String meInviteCode, Long sj) {
        // TODO Auto-generated method selectFansTodaySum
        return appUserMapper.selectFansDaySuperInviteMeInviteCodeSum(meInviteCode, sj);
    }

    private int selectFansBySuperInviteCodeSum(String meInviteCode) {
        // TODO Auto-generated method stub

        return appUserMapper.selectFansBySuperInviteCodeSum(meInviteCode);
    }

    private int selectFansBySuperInviteMeInviteCodeSum(String meInviteCode) {
        // TODO Auto-generated method stselectFansBySuperInviteMeInviteCodeCodeSumub
        return appUserMapper.selectFansBySuperInviteMeInviteCodeSum(meInviteCode);
    }

    /**
     * 根据userId查询用户详情-从redis或者数据库
     *
     * @param userId
     * @param type   1实时从数据库2优先从redis
     * @return
     */
    @Override
    public AppUser selectAppUserByUserId(Long userId, int type) {
        if (userId == null) {
            return null;
        }

        // TODO Auto-generated method stub
        String redisKeyStr = "app_user_info_" + userId;
        AppUser appUser = null;
        if (type == 1 && redisTemplateService.hasKey(redisKeyStr)) {
            appUser = redisTemplateService.getTByKey(redisKeyStr, AppUser.class);
        }
        if (appUser == null || appUser.getUserId() == null || appUser.getUserId() == 0) {
            appUser = appUserMapper.selectAppUserByUserId(userId);
            if (appUser != null) {
                redisTemplateService.set(redisKeyStr, appUser, 60 * 30);
            }
        }
        return appUser;

    }

    /**
     * 根据userId查询用户详情
     *
     * @param userId
     * @return
     */
    @Override
    public AppUser selectAppUserByUserId(long userId) {
        // TODO Auto-generated method stub
        return appUserMapper.selectAppUserByUserId(userId);
    }

    //判断当前时间是不是在30天以内
    public static Boolean is30Time(Long a) {
        //获取注册时间第N天后的时间
        if (System.currentTimeMillis() < getDateTime(a, ApiEnum.FENS_EXPIRE_TIME)) {
            return true;
        } else {
            return false;
        }
    }

    // 获取指定时间的时间戳
    private static long getDateTime(Long a, Integer start) {

        return DateUtils.addDays(new Date(a), start).getTime();
    }

    @Override
    public Long selectUserCount() {
        return appUserMapper.selectUserCount();
    }

    @Override
    public Integer selectRegistUser(Long channelId, Integer flag) {
        return appUserMapper.selectRegistUser(channelId, flag);
    }

    @Override
    public List<ChannelUserAffiliationVo> selectChannelUserNotAffiliation() {
        return appUserMapper.selectChannelUserNotAffiliation();
    }

    /**
     * 根据用户id，修改所属公司
     * @param userId
     * @param companyId
     * @return
     */
    @Override
    public int updateAppUserCompanyByUserId(Long userId, Integer companyId) {
        return appUserMapper.updateAppUserCompanyByUserId(userId,companyId);
    }
    @Override
    public List<AppUser> selectAppUserByTaobaoId(String taobaoUserId){
        return appUserMapper.selectAppUserByTaobaoId(taobaoUserId);
    }

    @Override
    public Integer sqjdRegistNum() {

        return appUserMapper.sqjdRegistNum();
    }

    @Override
    public Integer sqjdAllRegistNum() {
        return appUserMapper.sqjdAllRegistNum();
    }

    @Override
    public Integer zgsAllRegistNum(Integer type) {
        return appUserMapper.zgsAllRegistNum(type);
    }

    @Override
    public Integer addPayOrder(Integer type) {
        return appUserMapper.addPayOrder(type);
    }
}
